use std::fs;
use std::error::Error;
use std::env;

pub struct Config1 {
    pub query: String,
    pub filename: String,
    pub case_sensitive: bool,
}

impl Config1 {
    pub fn new(args: &[String]) -> Result<Config1, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }
        let query = args[1].clone();
        let filename = args[2].clone();
        let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
        Ok(Config1 { query, filename ,case_sensitive})
    }
}

pub fn run(config: Config1) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.filename)?;
    // println!("With text:\n{}", contents);
    let results = if config.case_sensitive {
        search(&config.query, &contents)
    }else{
        search_case_insensitive(&config.query, &contents)
        
    };
    for line in results {
        println!("{}", line);
    }
    Ok(())
}

// tests
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
fn case_sensitive() {
    let query = "duct";
    let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
    assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
    let query = "rUsT";
    let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
    assert_eq!(
        vec!["Rust:", "Trust me."],
        search_case_insensitive(query, contents)
    );
}
}

/// 在给定的内容中搜索指定的查询字符串，并返回包含查询字符串的所有行。
///
/// # 参数
///
/// - `query`: &str - 要搜索的查询字符串。
/// - `contents`: &'a str - 要搜索的内容，通常是一个多行字符串。
///
/// # 返回值
///
/// - `Vec<&'a str>` - 一个字符串切片向量，每个切片代表一个包含查询字符串的行。
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    // 初始化一个空的向量，用于存储匹配的行
    let mut results = Vec::new();

    // 遍历内容的每一行
    for line in contents.lines() {
        // 检查当前行是否包含查询字符串
        if line.contains(query) {
            // 如果当前行包含查询字符串，则将其添加到结果向量中
            results.push(line);
        }
    }

    // 返回结果向量
    results
}

/// 在给定的内容中以不区分大小写的方式搜索指定的查询字符串。
///
/// # 参数
///
/// - `query`: &str - 需要搜索的查询字符串。
/// - `contents`: &'a str - 需要搜索的内容，通常是一个字符串的文本。
///
/// # 返回值
///
/// 返回一个`Vec<&'a str>`，包含所有匹配查询字符串的行。
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    // 将查询字符串转换为小写，以实现不区分大小写的搜索。
    let query = query.to_lowercase();
    // 初始化一个空的向量，用于存储搜索结果。
    let mut results = Vec::new();

    // 遍历内容的每一行，进行不区分大小写的搜索。
    for line in contents.lines() {
        // 如果当前行转换为小写后包含查询字符串，则将该行添加到结果中。
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    // 返回搜索结果。
    results
}

pub struct Config2 {
    pub query: String,
    pub filename: String,
    pub case_sensitive: bool,
}

impl Config2 {
    pub fn new(mut args: std::env::Args) -> Result<Config2, &'static str> { 
        args.next();
        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query string"),
        };
        let filename = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a file name"),
        };
        let case_sensitive = std::env::var("CASE_INSENSITIVE").is_err();
        Ok(Config2 {
            query,
            filename,
            case_sensitive,
        })
    }

    pub fn run(&self) -> Result<(), Box<dyn Error>> {
        let contents = fs::read_to_string(&self.filename)?;
        
        let results = if self.case_sensitive {
            self.search(&contents)
        } else {
            self.search_case_insensitive(&contents)
        };
        for line in results {
            println!("{}", line);
        }
        Ok(())
    }

    fn search<'a>(&self,contents: &'a str) -> Vec<&'a str> {
        contents
            .lines()
            .filter(|line| line.contains(&self.query))
            .collect()
    }

    fn search_case_insensitive<'a>(&self, contents: &'a str) -> Vec<&'a str> {
        contents
            .lines()
            .filter(|line| line.to_lowercase().contains(&self.query.to_lowercase()))
            .collect()
    }
}

